package com.zlzlib.libnetty.tcp.handler;


import com.zlzlib.libnetty.base.BaseClient;
import com.zlzlib.libnetty.util.Util;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Created by zlz on 2019/11/19.
 * 消息接收处理handler
 */
public class TCPReadHandler<T> extends ChannelInboundHandlerAdapter {

    private final BaseClient<T> imsClient;

    public TCPReadHandler(BaseClient<T> imsClient) {
        this.imsClient = imsClient;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        Util.logError("TCPReadHandler 断开连接");
        if (imsClient.getStatusListener() != null) {
            imsClient.getStatusListener().onConnectClose();
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        Util.logError("TCPReadHandler 连接异常=" + cause.getMessage());
        ctx.close();
        // 触发重连
        imsClient.resetConnect();
        if (imsClient.getStatusListener() != null) {
            imsClient.getStatusListener().onConnectException(cause);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
        Util.logInfo("收到服务端消息channelRead，message=" + obj);
        T msg = imsClient.getDataListener().changeMsgData(obj);
        if (imsClient.getDataListener().isDataEmpty(msg)) {
            return;
        }
        //判断是不是为了标识服务器接收或发送成功的消息
        if (imsClient.getDataListener().isServerSentReport(msg)) {
            if (imsClient.getDataListener().isServerSentReportSuccess(msg)) {
                Util.logInfo("收到服务端消息发送状态报告成功，message=" + msg + "，从超时管理器移除");
                imsClient.getMsgTimeoutTimerManager().remove(imsClient.getDataListener().getMsgId(msg));
            } else {
                Util.logInfo("收到服务端消息发送状态报告失败，message=" + msg);
            }
        } else {
            // 其它消息
            Util.logInfo("收到消息，message=" + msg);
            // 收到消息后，立马给服务端回一条消息接收状态报告
            T receivedReportMsg = imsClient.getDataListener().getReceivedReportMsg(msg);
            if (receivedReportMsg != null) {
                imsClient.sendMsg(receivedReportMsg);
            }
        }
        // 接收消息，由消息转发器转发到应用层
        imsClient.getMsgDispatcher().receivedMsg(msg);
    }
}
